package com.github.permissiondog.cancanpbackend.filter;

import com.github.permissiondog.cancanpbackend.model.User;
import com.github.permissiondog.cancanpbackend.response.BaseResponse;
import com.github.permissiondog.cancanpbackend.service.UserService;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "LoginFilter", value = { "/logout", "/resource/*", "/applicationInfo" })
public class LoginFilter extends BaseFilter {
    @Override
    public void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {
        if (resolveUser(req, res))
            super.doFilter(req, res, chain);
    }

    protected boolean resolveUser(HttpServletRequest req, HttpServletResponse res) throws IOException {
        Integer uid = (Integer) req.getSession().getAttribute("uid");
        if (uid == null) {
            json(res, BaseResponse.builder().ok(false).msg("尚未登陆").build());
            return false;
        }
        req.getServletContext().log("Filter uid: " + uid);
        User user = UserService.getInstance().getUserById(uid);
        if (user == null) {
            req.getSession().removeAttribute("uid");
            json(res, BaseResponse.builder().ok(false).msg("会话失效,请尝试请重新登录").build());
            return false;
        }
        req.setAttribute("user", user);
        return true;
    }
}
